﻿/// <reference path="/Js/jsUtil.js"/> 
/**
* 
*/
var X_DECORATEKEYS = ["毛坯", "简装", "中装", "豪装", "精装"];      //从0开始
var X_HOUSEFACE = ["多层", "小高层", "高层", "公寓", "商住", "门面", "商铺", "别墅", "厂房", "写字楼", "车库", "多层复式", "高层复式"];       //从0开始
var X_HOUSEFACE_NOTINGCHUWEI = [5, 6, 8, 10];
var X_SELLSTATE = ["在售", "停售", "已售", "删除", "签单"];//, "重复"];
var X_SELLSTATE_COLOR = ["green", "red", "blue", "red"];
var X_SUGGESTSTATE = ["普通", "包销", "限时", "必杀"];
var X_RENTSTATE = ["在租", "停租", "已租"];
var X_USERSTATE = ["正常", "停用", "删除"]; //客户也用这个
var X_STAFFSTATE = ["在职", "离职"];
var X_CUSTOMERSTATE = ["正常", "失效", "删除"];
var X_ONLINESTATE = ["在线", "离线", "不在线"];
var X_VIEWLEVEL = ["自己", "本部门", "所有"];
var StateKeys = { Normal: 'Normal', Stop: 'Stop', Delete: 'Delete', Already: 'Already', Duplicate: 'Duplicate' };
var ServiceStateKeys = { TimeOut: 'TimeOut', Success: 'Success', Fail: 'Fail', NoPermiss: 'NoPermiss', Exists: 'Exists', NotExists: 'NotExists', InUse: 'InUse', NotInUse: 'NotInUse' }
var OnLineState = { OnLine: 'OnLine', Leave: 'Leave', OffLine: 'OffLine' };
var X_WFSTATE = ["待办", "完成", "终止", "删除", "未通过"];// "结束", "终止", "删除"];
var X_RENTPAYTYPE = ['', "月付", '', "季付", '', '', "付半年", '', '', '', '', '', "付一年"];

var CRMTypeArray = ["求购", "求租", "按揭贷款", "抵押贷款"];
var InformationComeFrom = ["网络", "上门", "贴条", "亲戚朋友介绍", "老客户介绍", "其他形式"];
var X_CRM_SEX = ['女', '男', '未知'];
var X_CRM_STATE = ['正常', '无效', '删除'];

var PAYTYPEARRAY = ["一次性支付", "省直公积金", "市直公积金", "商业贷款", "市直加商贷", "省直加商贷", "自行贷款", "组合贷款"];
var CHARGEPAYTYPEARRAY = ["双方支付", "买方支付", "卖方支付", "包费用"];
var FOLLOWCMSTATE = ["未开始", "正常", "解除", "完成"];
var CM_STATE_ARRAY = ["未开始", "进行中", "终止", "完成"];
var CM_STEPS_STATE_ARRAY = ["未开始", "已完成", "已跳过"];
//标准宽度
var X_WIDTH = {
    Depart: 70,
    UserName: 45,
    Ip: 100,
    Time: 70,
    Building: 100,
    Sex: 30,
    Tel: 140,
    HardStr: 185,
    CheckStr: 185,
    Bool: 20,
    State: 35,
    Title: 300,
    Number: 40,
    RegionArea: 40,
    Int: 40,
    Floor: 50
};

var X_TAB_HEIGHT = 75;
//渲染用户控件，全是xclass-模块-功能
function renderUserControls(target) {
    //日期
    $(".easyui-datebox", target).each(function () {
        $(".easyui-datebox:not(.datebox-f)", target).each(function (a, v) {
            var newspan = $("<span></span>");
            $(v).after(newspan); $(v).attr("type", "hidden");
            $(v).addClass('datebox-f'); var oldVal = $(v).val();

            var dd = new Ext.form.DateField({
                width: 100, format: 'Y-m-d', emptyText: '请选择日期 ...', renderTo: newspan[0], listeners: {
                    change: function (t, newValue, oldValue) {
                        try {
                            $(v).val(newValue.format("yyyy-MM-dd")).change();
                        } catch (e) {
                            $(v).val('');
                        }
                    }
                }
            });
            $(v).attr("data-ext-id", dd.getId());
            $(v).change(function () {
                dd.setValue($(v).val().toDate());
            });
            if (oldVal) {
                dd.setValue(oldVal.toDate());
            }
        });
    });
    //公用区域
    $(".xclass-region-area-list", target).each(function () {
        var _select = $(this);
        ///已经写过的，不用重复再写一次
        if (_select.find("option")) {
            if (_select.find("option").length > 1)
                return true
        };
        var _selectval = _select.attr("value");
        _select.empty();
        _select.addOption("选择区域", "");
        for (var area_item in X_AREA) {
            _select.addOption(X_AREA[area_item].AreaName, X_AREA[area_item].AreaId);
        }
        if (_selectval)
            _select.val(_selectval);
        else
            _select.val('');
    });
    //区域，复选
    $(".xclass-region-area-multiselect", target).each(function (a, v) {
        $(".xclass-region-area-multiselect:not(.region-f)", target).each(function (a, v) {
            var _id = parseInt(Math.random() * 100000);
            var newspan = $("<span></span><input id='temp{0}' type='hidden' name='{1}' />".format(_id, $(v).attr("name"))); $(v).after(newspan); $(v).css("display", "none"); $(v).addClass('region-f');

            var oldVal = $(v).val();
            var width = $(v).width();
            if (!width) width = 200;
            if (width < 98) width = 200;
            $(v).attr("name", $(v).attr("name") + "_T");

            var datas = [];
            for (var t in X_AREA) {
                datas.push({ AreaName: X_AREA[t].AreaName, AreaId: X_AREA[t].AreaId });
            }
            var states = Ext.create('Ext.data.Store', {
                fields: ['AreaId', 'AreaName'],
                data: datas
            });
            var dd = Ext.create('Ext.form.ComboBox', {
                width: width, fieldLabel: '', store: states, multiSelect: true, editable: false, queryMode: 'local', displayField: 'AreaName', valueField: 'AreaId', renderTo: newspan[0], listeners: {
                    change: function (t, newValue, oldValue) {
                        if (newValue) {
                            $("input#temp{0}".format(_id), target).val(newValue.join(','));
                        }
                    }
                }
            });
            $(v).attr("data-ext-id", dd.getId());
        });

    });
    //用户,自动建议
    if ($(".xclass-rbac-user:not(.combobox)", target).length) {
        $(".xclass-rbac-user:not(.combobox)", target).each(function (k, v) {
            var newspan = $("<span></span><input type='hidden' name='{0}' />".format($(v).attr("name") + "_Names")); $(v).after(newspan); $(v).attr("type", "hidden"); $(v).addClass('combobox');
            var oldVal = $(v).val();
            var url = "/RBAC/Services/RBAC_Users.asmx/GetLists";
            var myStore = new Ext.data.Store({
                fields: ['UserId', 'UserName'],
                pageSize: 10, autoLoad: true, remoteFilter: true, autoDestroy: true,
                proxy: {
                    type: 'ajax', url: url, pageParam: 'page', startParam: '{startParam}', limitParam: 'rows', headers: { "Content-Type": 'application/json' },
                    reader: { rootProperty: 'd.Table.rows', totalProperty: 'd.Total' }
                }
            });
            var cb = new Ext.form.ComboBox({
                store: myStore, valueField: 'UserId', displayField: 'UserName', queryParam: 'UserName', minChars: 1, renderTo: newspan[0],
                listConfig: { loadingText: '正在查找...', emptyText: '没有找到匹配的数据' }, listeners: {
                    change: function (t, newValue) {
                        $(v).val(newValue);
                        if (t.valueModels) {
                            $(v).attr("data-area", t.valueModels[0].data.UserName);
                            $("input[name=" + $(v).attr("name") + "_Names]").val(t.valueModels[0].data.UserName);
                        }
                        $(v).change();
                    }
                }
            });
            myStore.load({ params: { start: 0, limit: 10 } });
        });
    }
    //装修方式
    $(".xclass-decorate", target).each(function () {
        var _select = $(this);
        var _selectval = _select.attr("value");
        _select.empty();
        _select.addOption("选择装修", "");
        for (var _d = 0; _d < X_DECORATEKEYS.length; _d++) {
            _select.addOption(X_DECORATEKEYS[_d], _d);
        }
        if (_selectval)
            _select.val(_selectval);
        else
            _select.val('');
    });
    //装修复选 
    $(".xclass-decorate-multiselect", target).each(function () {
        $(".xclass-decorate-multiselect:not(.decorate-f)", target).each(function (a, v) {
            var _id = parseInt(Math.random() * 100000);
            var newspan = $("<span></span><input id='temp{0}' type='hidden' name='{1}' />".format(_id, $(v).attr("name"))); $(v).after(newspan); $(v).css("display", "none"); $(v).addClass('decorate-f');

            var oldVal = $(v).val();
            $(v).attr("name", $(v).attr("name") + "_T");

            var datas = [];
            for (var i = 0; i < X_DECORATEKEYS.length; i++) {
                datas.push({ Name: X_DECORATEKEYS[i], Id: i });
            }
            var states = Ext.create('Ext.data.Store', {
                fields: ['Id', 'Name'],
                data: datas
            });
            Ext.create('Ext.form.ComboBox', {
                width: 100, fieldLabel: '', store: states, multiSelect: true, editable: false, queryMode: 'local', displayField: 'Name', valueField: 'Id', renderTo: newspan[0], listeners: {
                    change: function (t, newValue, oldValue) {
                        $("input#temp{0}".format(_id), target).val(newValue.join(','));
                    }
                }
            });
        });
    });
    //小区
    if ($(".xclass-region-building:not(.combobox)", target).length) {
        $(".xclass-region-building:not(.combobox)", target).each(function (k, v) {
            var newspan = $("<span></span><input type='hidden' name='{0}' />".format($(v).attr("name") + "_Names")); $(v).after(newspan); $(v).attr("type", "hidden"); $(v).addClass('combobox');
            var oldVal = $(v).val();

            var url = "/Region/Services/Region_Buildings.asmx/GetLists";
            var myStore = new Ext.data.Store({
                fields: ['BuildingId', 'BuildingName'],

                pageSize: 10,
                autoLoad: true, remoteFilter: true, autoDestroy: true,
                proxy: {
                    type: 'ajax',
                    url: url,
                    pageParam: 'page',
                    startParam: '{startParam}', limitParam: 'rows',
                    headers: { "Content-Type": 'application/json' },
                    reader: {
                        rootProperty: 'd.Table.rows',
                        totalProperty: 'd.Total'
                    }
                }
            });
            var cb = new Ext.form.ComboBox({
                store: myStore,
                width: 140,
                valueField: 'BuildingId',
                displayField: 'BuildingName',
                queryParam: 'txtBuildName',
                minChars: 1,
                renderTo: newspan[0],//$(v)[0],
                listConfig: {
                    loadingText: '正在查找...',
                    emptyText: '没有找到匹配的数据'
                },
                listeners: {  //为Combo添加select事件
                    change: function (t, newValue) {   // 该事件会返回选中的项对应在 store中的 record值. index参数是排列号.
                        $(v).val(newValue);
                        if (t.valueModels) {
                            try {
                                //if (typeof (t.valueModels) == 'Array') {
                                $(v).attr("data-area", t.valueModels[0].data.BuildingArea);
                                $("input[name=" + $(v).attr("name") + "_Names]").val(t.valueModels[0].data.BuildingName);
                                //}
                            } catch (e) { }
                        }
                        $(v).change();
                    }
                }
            });
            $(v).attr("ext-comobobox-id", cb.getId());
            myStore.load({ params: { start: 0, limit: 10 } });
        });
    }
    //房屋类型
    $(".xclass-house-type", target).each(function (k, v) {
        var _select = $(this);
        var _selectval = _select.attr("value");
        _select.empty();
        _select.addOption("物业类型", "");
        for (var _k = 0; _k < X_HOUSEFACE.length; _k++) {
            _select.addOption(X_HOUSEFACE[_k], _k);
        }
        if (_selectval)
            _select.val(_selectval);
        else
            _select.val('');
    });
    //部门，树形下拉菜单
    if ($(".xclass-org-departs", target).length) {
        /**下拉机构数*/
        $(".xclass-org-departs", target).each(function (k, v) {
            var newspan = $("<span></span>");
            if ($(v).attr("type") == 'hidden') return true;
            $(v).attr("type", "hidden");
            $(v).after(newspan);
            var oldVal = $(v).val();
            Ext.require('Org.Js.Departs_Module', function () {
                var tree = Org.Js.Departs_Module.Tree;
                var treepicker = Ext.create('Js.TreePicker', {
                    displayField: 'DepartName', fieldLabel: '', forceSelection: true, editable: false, renderTo: newspan[0],
                    minPickerWidth: 200, valueField: 'DepartId', resizable: true,// autoScroll: true,
                    store: Ext.create('Ext.data.TreeStore', {
                        fields: ['DepartId', 'DepartName'], collapsible: true,
                        rootVisible: true,
                        root: {
                            children: tree.rows[0].children, expanded: true,
                            DepartName: '公司', DepartId: 0
                        }
                    }), height: 0,
                    listeners: {
                        select: function (field, value) {
                            if (field.value == 'root')
                                $(v).val(1);
                            else
                                $(v).val(field.value.replace("DepartId", ""));
                        }
                    }
                });
                if (oldVal) {
                    treepicker.setValue('DepartId' + oldVal);
                }
                $(v).attr("data-id", treepicker.getId());
                $(v).change(function (a) {
                    treepicker.setValue('DepartId' + $(this).val());
                });
            });
        });
    }
    //部门id转部门名称
    if ($(".xclass-org-formatDepart", target).length) {
        $(".xclass-org-formatDepart", target).each(function (k, v) {
            var _select = $(v);
            var _selectval = _select.val();
            _select.val(formatDepart(_selectval));
        });
    }
    //姓名id转姓名
    if ($(".xclass-org-formatUser", target).length) {
        $(".xclass-org-formatUser", target).each(function (k, v) {
            var _select = $(v);
            var _selectval = _select.val();
            _select.val(formatUser(_selectval));
        });
    }
    //
    if ($(".xclass-org-departs-select", target).length) {
        $(".xclass-org-departs-select", target).each(function (k, v) {
            var _select = $(v);
            _select.empty();
            _select.addOption("-选择门店或部门-", "0");
            for (var _depart in X_DEPARTS) {
                var _temp = X_DEPARTS[_depart];
                if (_temp.IsVirtual == 'False')
                    _select.addOption(_temp.DepartName, _temp.DepartId);
            }
            if (_select.attr("value1")) {
                _select.val(_select.attr("value1"));
                _select.change();
            }
        });
    }

    //部门用户联动,预设值value1 userid
    if ($(".xclass-org-departs-users", target).length) {
        $(".xclass-org-departs-users", target).each(function (k, v) {
            var _select = $(v);
            _select.empty();
            _select.addOption("-选择门店或部门-", "0");
            for (var _depart in X_DEPARTS) {
                var _temp = X_DEPARTS[_depart];
                if (_temp.IsVirtual == 'False')
                    _select.addOption(_temp.DepartName, _temp.DepartId);
            }
            if (_select.attr("value1")) _select.val(_select.attr("value1"));

            if (!_select.next().hasClass("xclass-org-departs-users-extension")) {
                _select.after("<select name='UserId' class='xclass-org-departs-users-extension'><option value=''>选择用户</option></select>");
                var _selectUser = _select.next();
                if (_select.attr("userid")) _selectUser.attr("value1", _select.attr("userid"));
                _select.change(function () {
                    _selectUser.xBindData({
                        "url": "/RBAC/Services/RBAC_Users.asmx/GetLists",
                        "data": { txtDeparts: $(this).val(), page: 1, rows: 15, isTree: true },
                        "text": "UserName",
                        "value": "UserId"
                    });
                });

            }
            if (_select.attr("value1")) _select.change();
        });
    }

    //部门用户联动,合同管理中使用
    if ($(".xclass-org-departs-signssers", target).length) {
        $(".xclass-org-departs-signssers", target).each(function (k, v) {
            var _select = $(v);
            _select.empty();
            _select.addOption("-选择门店或部门-", "0");
            for (var _depart in X_DEPARTS) {
                var _temp = X_DEPARTS[_depart];
                if (_temp.IsVirtual == 'False')
                    _select.addOption(_temp.DepartName, _temp.DepartId);
            }
            if (_select.attr("value1")) _select.val(_select.attr("value1"));

            if (!_select.next().hasClass("xclass-org-departs-users-extension")) {
                _select.after("<select name='SignUserId' class='xclass-org-departs-users-extension'><option value=''>选择签单人</option></select>");
                var _selectUser = _select.next();
                if (_select.attr("userid")) _selectUser.attr("value1", _select.attr("userid"));
                _select.change(function () {
                    _selectUser.xBindData({
                        "url": "/RBAC/Services/RBAC_Users.asmx/GetLists",
                        "data": { txtDeparts: $(this).val(), page: 1, rows: 15, isTree: true },
                        "text": "UserName",
                        "value": "UserId"
                    });
                });

            }
            if (_select.attr("value1")) _select.change();
        });
    }
    //职位,普通下拉菜单
    if ($(".xclass-org-posts", target).length) {
        $(".xclass-org-posts", target).each(function (k, v) {
            var _select = $(v);
            var _selectval = _select.val();
            _select.empty();
            _select.addOption("请选择职位名称", "");
            for (var _post in X_POSTS) {
                _select.addOption(X_POSTS[_post].PostName, _post.replace('_', ''));
            }
            if (_selectval)
                _select.val(_selectval);
            else
                _select.val('0');
        });
    }
    if ($(".xclass-house-shi:not(.numberspinner-f)", target).length) {
        //室
        $(".xclass-house-shi:not(.numberspinner-f)", target).each(function (a, v) {
            var newspan = $("<span></span>"); $(v).after(newspan); $(v).attr("type", "hidden"); $(v).addClass('numberspinner-f');
            var oldVal = $(v).val();
            new Ext.form.NumberField({
                width: 60, xtype: 'numberfield', anchor: '100%', name: '', fieldLabel: '室', labelWidth: 12, value: oldVal, maxValue: 20, renderTo: newspan[0], minValue: 0, listeners: {
                    change: function (t, newValue, oleValue) {
                        $(v).val(newValue);
                    }
                }
            });
        });

    }
    //厅
    if ($(".xclass-house-ting:not(.numberspinner-f)", target).length) {
        $(".xclass-house-ting:not(.numberspinner-f)", target).each(function (a, v) {
            var newspan = $("<span></span>"); $(v).after(newspan); $(v).attr("type", "hidden"); $(v).addClass('numberspinner-f'); var oldVal = $(v).val();
            new Ext.form.NumberField({
                width: 60, xtype: 'numberfield', anchor: '100%', name: '', fieldLabel: '厅', labelWidth: 12, value: oldVal, maxValue: 20, renderTo: newspan[0], minValue: 0, listeners: {
                    change: function (t, newValue, oleValue) {
                        $(v).val(newValue);
                    }
                }
            });
        });
    }
    if ($(".xclass-house-chu:not(.numberspinner-f)", target).length) {

    }
    if ($(".xclass-house-wei:not(.numberspinner-f)", target).length) {

    }

    //label显示格式化出售
    if ($(".labelHouseSellState", target).length) {
        $(".labelHouseSellState", target).each(function (k, v) {
            var _select = $(v);
            var houseState = parseInt(_select.text());

            var cssStr = StateStrToJsonStr(houseState);
            _select.css($.parseJSON(cssStr))
            _select.text(X_SELLSTATE[houseState]);
        });
    }
    //label显示格式化出租
    if ($(".labelHouseRentState", target).length) {
        $(".labelHouseRentState", target).each(function (k, v) {
            var _select = $(v);
            var houseState = parseInt(_select.text());

            var cssStr = StateStrToJsonStr(houseState);
            _select.css($.parseJSON(cssStr))
            _select.text(X_RENTSTATE[houseState]);
        });
    }
    //label显示格式求购
    if ($(".labelCRMCustomerState", target).length) {
        $(".labelCRMCustomerState", target).each(function (k, v) {
            var _select = $(v);
            var houseState = parseInt(_select.text());

            var cssStr = StateStrToJsonStr(houseState);
            _select.css($.parseJSON(cssStr))
            _select.text(X_CUSTOMERSTATE[houseState]);
        });
    }
    //系统设置
    if ($(".System", target).length) {
        $(".System", target).each(function (k, v) {
            var _label = $(v);
            var _module = _label.attr("data-module");
            var _key = _label.attr("data-key");
            if (!RBAC.Js.RBAC_Module.SystemGetBool(_module, _key)) {
                _label.css("display", "none");
            } else
                _label.css("display", "block");
        });
    }
    //资源动作权限
    if ($(".Limit", target).length) {
        Ext.require('RBAC.Js.RBAC_Module', function () {

            $(".Limit", target).each(function (k, v) {
                var _label = $(v);
                var _resource = _label.attr("ResourceName");
                var _operation = _label.attr("OperationName");
                var _limit = RBAC.Js.RBAC_Module.CheckLimit(_resource, _operation);
                if (_limit)
                    _label.show();
                else
                    _label.hide();
            });
        });
    }
    //$("input.combobox-f", target).attr("type", "hidden");//配合Enter2Tab使用
}

function getChildren(node) {
    var _children = [];
    for (var _j in X_DEPARTS) {
        if (X_DEPARTS[_j].ParentId == node.DepartId) {
            _children.push({
                id: X_DEPARTS[_j].DepartId,
                text: X_DEPARTS[_j].DepartName,
                children: getChildren(X_DEPARTS[_j])
            });
        }
    }
    return _children;
}
///本系统easyui标准format
function formatDepart(v, r, k) {
    if (!v) return "";

    if (X_DEPARTS['_' + v])
        return X_DEPARTS['_' + v].DepartName;
    else
        return "";
}
//不能用在grid里
function formatUser(v) {
    var rowObj = getRemoteObject("/RBAC/Services/RBAC_Users.asmx/Query", { id: v });
    return rowObj.UserName;
}
///本系统easyui标准format
function formatPost(v, r, k) {
    if (!v) return "";

    if (X_POSTS['_' + v])
        return X_POSTS['_' + v].PostName;
    else
        return "";
}
///bool状态转为：启用 停用
function formatState(v, r, k) {
    if (v)
        return "启用";
    else
        return "停用";
}
///审核状态：未审 已审
function formatPassState(v, r, k) {
    if (v == '0')
        return "未审";
    else
        return "已审";
}
///bool状态转为：启用 停用
function formatHouseState(v, r, k) {
    if (v)
        return "启用";
    else
        return "停用";
}

//公用样式
function styleBool(v, r, k) {
    if (v) {
        return "background-color:green;color:#fff";
    }
    else {
        return "background-color:red;color:#fff";
    }
}
function styleHouseState(v, r, k) {
    switch (v) { //{ "正常", "停售","已售", "删除" }
        case 0:
            return 'background-color:#99CC33;color:#333';
            break;
        case 1:
            return 'background-color:red;color:#fff';
            break;
        case 2:
            return 'background-color:#6699CC;color:#fff';
            break;
        case 3:
            return 'background-color:red;color:#fff';
            break;
    }
}
function formatIsDelete(v, r, k) {
    if (v)
        return "删除";
    else
        return "未删";
}
function formatRegionArea(v, r, k) {
    return X_AREA['_' + v].AreaName;
}

//公用样式
function styleIsDelete(v, r, k) {
    if (v) {
        return "background-color:red;color:#fff";
    }
    else {
        return "background-color:green;color:#fff";
    }
}
function StateStrToJsonStr(v) {
    var str = styleHouseState(v);
    if (!str) return '{}';
    var arr = str.split(';');
    var result = "";
    for (var _j = 0; _j < arr.length; _j++) {
        var tempArr = arr[_j].split(':');
        if (result != "")
            result += ",";
        result += '"' + tempArr[0] + '":"' + tempArr[1] + '"';
    }
    result = '{' + result + '}';
    return result;
}

function loadFilter(data) {
    if (!data.d) {
        data.d = { Table: {} };
    }
    if (!data.d.Table) data.d.Table = {};
    if (data.d.Total)
        data.d.Table.total = data.d.Total;
    else
        data.d.Table.total = 0;
    if (!data.d.Table.rows) data.d.Table.rows = [];
    return data.d.Table;
}
function formatDecorations(c) {
    if (!c) return "";
    var _array = c.split(',');
    var result = "";
    for (var i = 0; i < _array.length; i++) {
        if (i > 0) result += ",";
        result += X_DECORATEKEYS[_array[i]];
    }
    return result;
}
function formatRegionAreas(c) {
    if (!c) return;
    var _array = c.split(',');
    var result = "";
    for (var i = 0; i < _array.length; i++) {
        if (i > 0) result += ",";
        result += X_AREA['_' + _array[i]].AreaName;
    }
    return result;
}
function formatTime(c) {
    return formatTimeBase(c, "yy/M/d h");
}
function formatShortTime(c) {
    return formatTimeBase(c, "yy-M-d h:m");
}
function formatDate(c) {
    return formatTimeBase(c, "yyyy-M-d");
}
function formatShortDate(c) {
    return formatTimeBase(c, "yy-M-d");
}
function formatYear(c) {
    return formatTimeBase(c, "yyyy");
}
function formatTimeBase(c, format) {
    if (!c) return "";
    if (c.indexOf("Date(") > -1) {
        var date_c;
        eval("date_c=new " + c.replaceAll("/", "") + ";");
        c = date_c.format(format);
    }
    else
        c = c.toDate().format(format);
    if (c.indexOf("NaN") > -1)
        return "";
    else
        return c;
}
function formatPrice(c, o, r) {
    return Math.round(parseFloat(c));
}
function formatBool(c, o, r) {
    return c ? "是" : "否";
}
function formatSex(c, o, r) {
    return c == "1" ? "男" : "女";
}
function formatDayClose(c, o, r) {
    var postName;
    if (!o.postId) postName = "";

    if (X_POSTS['_' + o.postId])
        postName = X_POSTS['_' + o.postId].PostName;
    else
        postName = "";

    return "点击查看详情--" + postName;
}
function formatDayContent(c,o,r) {
    return "点击查看详情"
}
(function () {
    ///把easyui的datagrid转换为ExtJs的表格
    $.fn.extend({
        datagrid: function (options) {
            var obj_this = this;

            if (options == 'reload') {//刷新表格
                var cmp = Ext.getCmp(obj_this.attr("data-id"));
                //cmp.store.proxy.url = opts.url;
                //cmp.store.proxy.extraParams = opts.data;
                cmp.store.reload();
                return;
            }

            var defaults = { width: '100%' };
            var opts = $.extend(defaults, options);
            if (!obj_this.hasClass("data-table")) {
                //表格初始化
                obj_this.addClass("data-table");

                var obj = $("<div></div>");
                obj_this.after(obj);
                var Store = Ext.create('Ext.data.Store', { //store和model一起创建
                    fields: [opts.idFiled],
                    pageSize: opts.pageSize,
                    autoLoad: true,
                    proxy: {
                        type: 'ajax',
                        enablePaging: opts.pagination,//支持翻页
                        url: opts.url,
                        method: opts.method,
                        pageParam: 'page',
                        startParam: '',
                        limitParam: 'rows',
                        headers: opts.headers,
                        reader: {
                            type: 'json',
                            rootProperty: 'd.Table.rows',
                            totalProperty: 'd.Total'
                        },
                        writer: {
                            type: 'json'
                        },
                        extraParams: opts.data,
                        sortParam: 'LastTime'
                    }
                });
                var Columns = easyui2extgrid(opts.columns);

                var grid = Ext.create('Ext.grid.Panel', {
                    scroll: true, height: opts.height,
                    store: Store, width: opts.width, forceFit: true,
                    columns: Columns,
                    listeners: {
                        rowclick: function (grid, row) {
                            if (opts.onClickRow) {
                                opts.onClickRow(row.rowIndex, row.data);
                            }
                        },
                        afterrender: function (t, eOpts) {

                        }
                    },
                    bbar: Ext.create('Ext.PagingToolbar', {
                        store: Store,
                        displayInfo: true,
                        displayMsg: '显示 {0} - {1} 条，共计 {2} 条',
                        emptyMsg: "没有数据"
                    }),
                    renderTo: obj[0]
                });
                obj_this.attr("data-id", grid.getId());
            } else {
                var cmp = Ext.getCmp(obj_this.attr("data-id"));
                cmp.store.proxy.url = opts.url;
                cmp.store.proxy.extraParams = opts.data;
                cmp.store.reload();
            }
        }
    });
    //把easyui的验证控件重定义
    $.fn.extend({
        form: function (opt) {
            if (opt == "validate") {
                var objForm = this;

                var isPass = true; var currentObj;
                $(".easyui-validatebox", objForm).each(function (k, item) {
                    //处理data-options
                    currentObj = $(item);
                    var options = currentObj.attr("data-options");

                    if (options) {
                        options = options.replace(/(\d+),(\d+)/, "$1|||$2");//针对 length=[3,20]这种写法，先把,换成|||

                        var array = options.split(',');
                        for (var i = 0; i < array.length; i++) {
                            var _temp = array[i].split(':');
                            if (_temp.length > 1)
                                currentObj.attr(_temp[0], _temp[1].replaceAll("'", "").replaceAll('"', ''));
                        }
                    }
                    var val = currentObj.val();
                    if (currentObj.attr("required")) {
                        if (!val) {
                            isPass = false;
                            return false;
                        }
                    }
                    if (currentObj.attr("validType")) {
                        var validType = currentObj.attr("validType").replace("|||", ",");
                        if (!val) {
                            isPass = true;
                            return true;
                        }
                        if (validType.indexOf("length") > -1) {
                            //限定长度 data-options="required:true,validType:'length[3,60]'"
                            var len_array = validType.replace("length", "").replace("[", "").replace("]", "").split(',');
                            if (len_array.length > 1) {
                                if (val.length < len_array[0]) {
                                    isPass = false; return false;
                                } else if (val.length > len_array[1]) {
                                    isPass = true; return false;
                                }
                                else {
                                    isPass = true; return true;
                                }
                            }
                        }//length[3,60]
                        else if (validType.indexOf("minLength") > -1) {
                            var len = validType.replace("minLength", "").replace("[", "").replace("]", "");
                            if (len) {
                                if (val.length < len) { isPass = false; return false; }
                            }
                        }
                        else if (!val.chkType(validType)) { //正则表达式
                            isPass = false;
                            return false;
                        }
                    }
                });
                if (!isPass) {
                    if ((currentObj.attr("type") == "hidden") || (currentObj.prop("readonly"))) {
                        console.log('隐藏域是验证失败，注意添加data-error属性，否则无法提示错误。', currentObj);
                        $.messager.show({ title: '操作提示', msg: currentObj.attr("data-error") || '' });
                    } else {
                        currentObj.css("background-color", "#FFE7E7").focus();
                        currentObj.change(function () { $(this).css("background-color", ""); });
                        $.messager.show({ title: "操作提示", msg: "请检查表单内容。" });
                    }
                    return false;
                }
                return true;
            }
        }
    });
    //把easyui的messager转换为ExtJs的提示框
    $.messager = {
        show: function (opts) {
            //if (!opts.title) opts.title = '操作提示';
            //if (!Ext.toast)
                noty({ text: opts.msg, layout: "center", timeout: 5000 })
            //else
            //    Ext.toast(opts.msg, opts.title, "center");
        },
        confirm: function (title, msg, callback) {
            Ext.MessageBox.confirm(title, msg, function (r) {
                if (r == 'no') return;
                callback();
            });
        },
        progress: function (title, msg) {
            if (typeof (title) == 'string') {
                if (title == 'close') {
                    var commonProgressBar = Ext.getCmp('commonProgressBar');
                    if (commonProgressBar) {
                        commonProgressBar.destroy();
                    }
                }
            } else {
                var commonProgressBar = Ext.getCmp('commonProgressBar');
                if (commonProgressBar) { }
                else {
                    var commonProgressBar = Ext.create("Ext.ProgressBar", {
                        id: "commonProgressBar",
                        text: '准备中...',
                        renderTo: Ext.getBody()
                    });
                    commonProgressBar.wait({
                        interval: 100,
                        duration: 10000,
                        increment: 100,
                        text: '请稍等',
                        scope: this,
                        fn: function () {
                            commonProgressBar.destroy();
                        }
                    });
                }
            }
        },
        alert: function (title, msg, type) {
            Ext.toast(msg, title, "center");
        }
        //$.messager.progress({ title: '提示信息', msg: '系统检测，请稍候...' });
    };
    $.fn.extend({
        combotree: function (opts) {

        }
    });


})(jQuery);
var arg0, arg1, arg2;
$(document).ready(function () {
    //菜单
    $(document).on("click", ".jsFunc", function () {
        var _win_ = $(this).attr("win");
        var _arg0_ = $(this).attr("arg0");
        var _arg1_ = $(this).attr("arg1");
        var _arg2_ = $(this).attr("arg2");
        popMenu(_win_, _arg0_, _arg1_, _arg2_);
    });
});
function popMenu(_win_, _arg0, _arg1, _arg2) {
    arg0 = _arg0;
    arg1 = _arg1;
    arg2 = _arg2;
    var win = _win_.replaceAll("/", ".");
    win = win.trim('.');
    try {
        var obj = Ext.create(win);
        return obj.show(_arg0, _arg1, _arg2);
    }
    catch (e) {
        var _path = _win_; //js路径  
        var _winName = _path.replaceAll("/", ""); //窗口名,就是无/的路径

        var isRoot = (_path.indexOf("/") == 0);
        if (isRoot) _path = _path.substring(1, _path.length); //去掉路径开头的/
        //if ($("#" + _winName).height() == null) {
        $.getScript((isRoot ? "/" : "Js/") + _path + ".js?r=" + Math.random());
        //}
        //else
        //    $("#" + _winName).dialog("open");
    }
}
//把easyui的表格定义改为Extjs的Grid表格定义
function easyui2extgrid(source) {
    var Columns = [];
    $.each(source[0], function (k, item) {
        Columns.push({
            text: item.title, dataIndex: item.field, width: item.width, align: item.align, hidden: item.hidden,
            renderer: function (v, k, r) {
                if (item.formatter)
                    return item.formatter(v, r.data, k);
                else
                    return v;
            }//( item.formatter)
        });
    });
    return Columns;
}
